package arrAndstr;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/*
    71. 简化路径
 */
public class T71 {
    public static void main(String[] args) {
        String path = "/home/of/foo/../../bar/../../is/./here/.";
        System.out.println(simplifyPath(path));
    }

    public static String simplifyPath(String path) {
        Stack<String> stack = new Stack<>();
        String[] split = path.split("/");
        for (String s : split) {
            if (!s.equals(".") && !s.equals("")){
                stack.add(s);
            }
        }
        List<String> list = new ArrayList<>();

        while (!stack.isEmpty()) {
            String str = stack.pop();
            switch (str){
                case ".": break;
                case "": break;
                case "..": {
                    int popCount = 1;
                    while (!stack.isEmpty() && stack.peek().equals("..")) {
                        stack.pop();
                        popCount++;
                    }
                    while (popCount>0 && !stack.isEmpty()) {
                        popCount--;
                        if (stack.peek().equals("..")) {
                            popCount+=2;    // 上面弹出了一次
                        }
                        stack.pop();
                    }
                    break;
                }
                default: list.add(str);
            }
        }
        StringBuffer sb = new StringBuffer("/");
        for (int i = list.size()-1; i >=0; i--) {
            sb.append(list.get(i));
            if (i!=0) sb.append("/");
        }
        return sb.toString();
    }
}
